package cn.szsys.integration.util;

import cn.szsys.integration.util.listener.OkHttpListener;
import com.alibaba.fastjson2.JSON;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.HttpStatus;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author Ryan
 * @since 2025-05-09
 **/
@Slf4j
public class OkHttpUtil {
    private static volatile OkHttpClient okHttpClient = null;
    private static volatile Semaphore semaphore = null;
    private Map<String, String> headerMap;
    private Map<String, Object> paramMap;
    private String url;
    private Request.Builder request;
    private String originRequestJson;


    /**
     * 初始化okHttpClient，并且允许https访问
     */
    private OkHttpUtil(int connectTimeout, int writeTimeout, int readTimeout) {
        if (okHttpClient == null) {
            synchronized (OkHttpUtil.class) {
                if (okHttpClient == null) {
                    TrustManager[] trustManagers = buildTrustManagers();
                    okHttpClient = new OkHttpClient.Builder()
                            .connectTimeout(connectTimeout, TimeUnit.SECONDS)
                            .writeTimeout(writeTimeout, TimeUnit.SECONDS)
                            .readTimeout(readTimeout, TimeUnit.SECONDS)
                            .sslSocketFactory(createSSLSocketFactory(trustManagers), (X509TrustManager) trustManagers[0])
                            .hostnameVerifier((hostName, session) -> true)
                            .retryOnConnectionFailure(true)
                            .eventListenerFactory(OkHttpListener.FACTORY)
                            .build();
                    addHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36");
                }
            }
        }
    }

    /**
     * 用于异步请求时，控制访问线程数，返回结果
     */
    private static Semaphore getSemaphoreInstance() {
        //只能1个线程同时访问
        synchronized (OkHttpUtil.class) {
            if (semaphore == null) {
                semaphore = new Semaphore(0);
            }
        }
        return semaphore;
    }

    /**
     * 创建OkHttpUtils
     */
    public static OkHttpUtil builder() {
        return new OkHttpUtil(15, 20, 20);
    }

    /**
     * 创建OkHttpUtils
     */
    public static OkHttpUtil builder(int connectTimeout, int writeTimeout, int readTimeout) {
        return new OkHttpUtil(connectTimeout, writeTimeout, readTimeout);
    }

    /**
     * 添加url
     *
     * @param url 请求地址
     */
    public OkHttpUtil url(String url) {
        this.url = url;
        return this;
    }

    /**
     * 添加参数
     *
     * @param key   参数名
     * @param value 参数值
     */
    public OkHttpUtil addParam(String key, Object value) {
        if (paramMap == null) {
            paramMap = new LinkedHashMap<>(16);
        }
        paramMap.put(key, value);
        return this;
    }

    /**
     * 添加请求头
     *
     * @param key   参数名
     * @param value 参数值
     */
    public void addHeader(String key, String value) {
        if (headerMap == null) {
            headerMap = new LinkedHashMap<>(16);
        }
        headerMap.put(key, value);
    }

    /**
     * 添加请求头
     *
     * @param headers headers
     */
    public OkHttpUtil addHeaders(Map<String, String> headers) {
        if (headerMap == null) {
            headerMap = new LinkedHashMap<>(16);
        }
        headerMap.putAll(headers);
        return this;
    }

    /**
     * 初始化get方法
     */
    public OkHttpUtil get() {
        request = new Request.Builder().get();
        StringBuilder urlBuilder = new StringBuilder(url);
        if (paramMap != null) {
            urlBuilder.append("?");
            for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
                urlBuilder.append(entry.getKey()).
                        append("=").
                        append(entry.getValue().toString()).
                        append("&");
            }

            urlBuilder.deleteCharAt(urlBuilder.length() - 1);
        }
        request.url(urlBuilder.toString());
        return this;
    }

    /**
     * 初始化post方法
     *
     * @param isJsonPost true等于json的方式提交数据，类似postman里post方法的raw
     *                   false等于普通的表单提交
     */
    public OkHttpUtil post(boolean isJsonPost) {
        RequestBody requestBody;
        if (isJsonPost) {
            String json = "";
            if (paramMap != null) {
                json = JSON.toJSONString(paramMap);
            }
            originRequestJson = json;
            requestBody = RequestBody.Companion.create(json, MediaType.parse("application/json; charset=utf-8"));
        } else {
            FormBody.Builder formBody = new FormBody.Builder();
            if (paramMap != null) {
                for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
                    formBody.add(entry.getKey(), entry.getValue().toString());
                }
            }
            requestBody = formBody.build();
        }
        request = new Request.Builder().post(requestBody).url(url);
        return this;
    }

    /**
     * post json传参
     *
     * @param requestJson requestJson
     * @return {@link OkHttpUtil}
     * @author rhf
     */
    public OkHttpUtil post(String requestJson) {
        originRequestJson = requestJson;
        RequestBody requestBody = RequestBody.Companion.create(requestJson, MediaType.parse("application/json; charset=utf-8"));
        request = new Request.Builder().post(requestBody).url(url);
        return this;
    }

    /**
     * 同步请求
     */
    public OkhttpResponse sync() {
        OkhttpResponse okhttpResponse = new OkhttpResponse();
        setHeader(request);
        try (Response response = okHttpClient.newCall(request.build()).execute()) {
            log.info("OkHttpClient,response[{}]", response.toString());
            if (response.isSuccessful()) {
                onSuccess(response, okhttpResponse);
            } else {
                onFail(response, okhttpResponse);
            }
            return okhttpResponse;
        } catch (IOException e) {
            log.error("okhttp同步请求异常,error msg:{}, e: ", e.getMessage(), e);
            onFail(okhttpResponse, e);
        }
        return okhttpResponse;
    }

    /**
     * 异步请求，有返回值
     */
    public String async() {
        StringBuilder buffer = new StringBuilder();
        setHeader(request);
        okHttpClient.newCall(request.build()).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                log.error("okhttp异步请求异常,error msg:{}, e: ", e.getMessage(), e);
                getSemaphoreInstance().release();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                buffer.append(response.body().string());
                getSemaphoreInstance().release();
            }
        });
        try {
            getSemaphoreInstance().acquire();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.error("okhttp异步请求信号量获取异常,error msg:{}, e: ", e.getMessage(), e);
        }
        return buffer.toString();
    }

    /**
     * 异步请求，带有接口回调
     */
    public void async(ICallBack callBack) {
        setHeader(request);
        okHttpClient.newCall(request.build()).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                callBack.onFailure(call, e.getMessage());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                callBack.onSuccessful(call, response.body().string());
            }
        });
    }

    /**
     * 为request添加请求头
     */
    private void setHeader(Request.Builder request) {
        if (headerMap != null) {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                request.addHeader(entry.getKey(), entry.getValue());
            }
        }
    }


    /**
     * 生成安全套接字工厂，用于https请求的证书跳过
     */
    private static SSLSocketFactory createSSLSocketFactory(TrustManager[] trustAllCerts) {
        SSLSocketFactory ssfFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new SecureRandom());
            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
            log.error("创建ssl连接异常,error msg:{}, e: ", e.getMessage(), e);
        }
        return ssfFactory;
    }

    private static TrustManager[] buildTrustManagers() {
        return new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
    }

    /**
     * 成功
     * @author Ryan
     * @param response response
     * @param okhttpResponse okhttpResponse
     */
    public void onSuccess(Response response, OkhttpResponse okhttpResponse) throws IOException {
        Headers headers = response.headers();
        Request build = request.build();
        ResponseBody responseBody = response.body();
        String body = responseBody == null ? "" : responseBody.string();
        log.info("okHttp request success, url[{}], method[{}], requestHeader -> [{}], requestBody -> [{}], responseHeader -> [{}], responseBody -> [{}]",
                build.url(), build.method(), build.headers(), originRequestJson, headers, body);
        okhttpResponse.success(body, headers);
        okhttpResponse.setCode(response.code());
    }

    /**
     * 组装返回
     *
     * @param okhttpResponse okhttpResponse
     * @param e              e
     * @author Ryan
     */
    public void onFail(OkhttpResponse okhttpResponse, Exception e) {
        if (e instanceof SocketTimeoutException) {
            Request build = request.build();
            log.error("okHttp request timeout[{}], url[{}], method[{}], header -> [{}], body -> [{}]", e.getMessage(),
                    build.url(), build.method(), build.headers(), originRequestJson, e);
            okhttpResponse.fail(HttpStatus.REQUEST_TIMEOUT.value(), e.getMessage());
            return;
        }
        Request build = request.build();
        log.error("okHttp request failure[{}], url[{}], method[{}], header -> [{}], body -> [{}]", e.getMessage(),
                build.url(), build.method(), build.headers(), originRequestJson, e);
        okhttpResponse.fail(HttpStatus.EXPECTATION_FAILED.value(), e.getMessage());
    }

    /**
     * 组装返回
     *
     * @param response       response
     * @param okhttpResponse okhttpResponse
     * @author Ryan
     */
    public void onFail(Response response, OkhttpResponse okhttpResponse) throws IOException {
        Headers responseHeaders = response.headers();
        Request build = request.build();
        ResponseBody responseBody = response.body();
        String responseBodyStr = responseBody == null ? "" : responseBody.string();
        String message = response.message();
        log.error("okHttp request failure[{}], url[{}], method[{}], requestHeader -> [{}], requestBody -> [{}], responseHeader -> [{}], responseBody -> [{}]", message,
                build.url(), build.method(), build.headers(), originRequestJson, responseHeaders, responseBodyStr);
        okhttpResponse.fail(response.code(), message);
        okhttpResponse.setData(responseBodyStr);
        okhttpResponse.setHeaders(responseHeaders);
    }


    /**
     * 自定义一个接口回调
     */
    public interface ICallBack {

        void onSuccessful(Call call, String data);

        void onFailure(Call call, String errorMsg);

    }


    @Data
    public static class OkhttpResponse {

        private Boolean success = true;

        /**
         * code编码
         */
        private int code;

        /**
         * 返回内容
         */
        private String msg;

        /**
         * 数据
         */
        private String data;

        /**
         * 请求头
         */
        private Headers headers;

        /**
         * 返回失败提示
         *
         * @param code        编码
         * @param description 内容
         * @return Result
         */
        public OkhttpResponse fail(int code, String description) {
            this.setSuccess(false);
            this.setCode(code);
            this.setMsg(description);
            return this;
        }

        /**
         * 返回成功
         *
         * @param data 参数
         * @return Result
         */
        public OkhttpResponse success(String data, Headers headers) {
            this.setSuccess(true);
            this.setCode(HttpStatus.OK.value());
            this.setData(data);
            this.setHeaders(headers);
            return this;
        }
    }
}

